//
//  AddWalletViewController.m
//  Wallets Manager
//
//  Created by Tung Nguyen on 9/30/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#import "AddWalletViewController.h"

@interface AddWalletViewController ()

@end

@implementation AddWalletViewController
{
    NSDate *currentDate;
}

@synthesize nameTextField;
@synthesize amoutTextField;
@synthesize currencyTextField;
@synthesize dateTextField;
@synthesize passwordTextField;
@synthesize descriptionTextField;
@synthesize scrollView;
@synthesize imagePickerButton;
@synthesize addButtonPressed;
@synthesize datePickerView,dateString,pickerViewPopup;
@synthesize activeTextField;
@synthesize currencyActionSheet,currencyPickerView;
@synthesize currencyArray;
@synthesize monthViewCalendar;


#pragma mark - Lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    scrollView.contentSize = CGSizeMake(320, 420);
    currentImageName = @"defaulticon.png";
    currencyArray = [[NSMutableArray alloc]initWithObjects:@"VND",@"USA Dollar",@"Pound",@"Australia Dollar",@"CNY",@"Euro", nil];
    
    //======================NSNotification ======================//
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getImageOnSuccess :) name:@"getImageOnSuccess" object:nil];
}

- (void)viewDidUnload
{
    [self setAddButtonPressed:nil];
    [self setScrollView:nil];
    [self setNameTextField:nil];
    [self setAmoutTextField:nil];
    [self setCurrencyTextField:nil];
    [self setDateTextField:nil];
    [self setPasswordTextField:nil];
    [self setDescriptionTextField:nil];
    [self setImagePickerButton:nil];
    
    self.monthViewCalendar  = nil;
    currentDate             = nil;
    currentImageName        = nil;
    pickerViewPopup         = nil;
    currencyActionSheet     = nil;
    datePickerView          = nil;
    currencyPickerView      = nil;
    
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Month View Delegate


- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
	return nil;
}

-(void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)date
{
    NSLog(@"%@", date);
    currentDate = date;
}

- (void) calendarMonthView:(TKCalendarMonthView*)monthView monthDidChange:(NSDate*)month animated:(BOOL)animated
{
    //NSLog(@"FRAME = %f X %f", monthView.frame.size.width , monthView.frame.size.height);
    [self performSelector:@selector(popUpRefreshFrame)];
}

#pragma mark - IBAction 

- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)addButtonPressed:(id)sender {
    // Format string to NSDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    NSDate * date = [dateFormatter dateFromString:dateTextField.text];
    
    double amountMoney = [amoutTextField.text doubleValue];
    
    [DataBaseAccess createWalletWithName:nameTextField.text andBalance:amountMoney andDate:date andPword:passwordTextField.text andImage:currentImageName];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"reloadTableView" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)imagePickerButtonClicked:(id)sender {
    ChooseWalletIconViewController *chooseWalletIconViewController = [[ChooseWalletIconViewController alloc]init];
    [self.navigationController pushViewController:chooseWalletIconViewController animated:YES];
}

-(IBAction)chooseDate:(id)sender
{
    [self createDatePickerView];
}

#pragma mark - Date PickerView

- (void)textFieldDidBeginEditing:(UITextField *)aTextField{
    // [aTextField resignFirstResponder];
    activeTextField = aTextField;
    
    if( aTextField == dateTextField) {
        [self createDatePickerView];
    }
    
    if( aTextField == currencyTextField) {
        [self createcurrencyPickerView];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    // [activeTextField release];
    activeTextField = nil;
    
}
-(void)doneDateButtonPressed:(id)sender{
    //Do something here here with the value selected using [pickerView date] to get that value
    if([dateString length] == 0) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"MM/dd/yyyy"];
        dateString = [dateFormatter stringFromDate:currentDate];
    }
    
    [dateTextField setText:dateString];
    [dateTextField resignFirstResponder];
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

-(void)cancelDateButtonPressed:(id)sender{
    
    //    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    //    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    //    [dateTextField setText:[dateFormatter stringFromDate:datePickerView.date]];
    [dateTextField resignFirstResponder];
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    //[currencyPickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)datePickerValueChanged:(id)sender{
    dateString = @"";
    UIDatePicker *picker = (UIDatePicker *)sender;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"MM/dd/yyyy"];
    
    dateString = [dateFormatter stringFromDate:picker.date];
    NSLog(@"%@",dateString);
}

- (void) createDatePickerView {
    
    if(pickerViewPopup == nil)
    {
        pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
    
     [pickerViewPopup setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
        
//    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];
//    datePickerView.datePickerMode = UIDatePickerModeDate;
//    datePickerView.hidden = NO;
//    datePickerView.date = [NSDate date];
//    [datePickerView addTarget:self action:@selector(datePickerValueChanged :) forControlEvents:UIControlEventValueChanged];
    
        UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        pickerToolbar.barStyle = UIBarStyleBlackOpaque;
        [pickerToolbar sizeToFit];
    
        NSMutableArray *barItems = [[NSMutableArray alloc] init];
    
        UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
        [barItems addObject:doneBtn];
    
        UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [barItems addObject:flexSpace];
    
        UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
        [barItems addObject:cancelBtn];
    
        [pickerToolbar setItems:barItems animated:YES];
    
        if(monthViewCalendar == nil)
        {
            monthViewCalendar = [[TKCalendarMonthView alloc] initWithSundayAsFirst:NO];
            monthViewCalendar.delegate  = self;
            monthViewCalendar.dataSource = self;
            //NSLog(@"MONTH %f x %f", monthViewCalendar.bounds.size.width, monthViewCalendar.bounds.size.height);
            [monthViewCalendar reload];
        }
        [monthViewCalendar setFrame:CGRectMake(0, 44, 320, monthViewCalendar.bounds.size.height)];
        pickerViewPopup.clipsToBounds=YES;
        
        //[pickerViewPopup addSubview:datePickerView];

        [pickerViewPopup addSubview:pickerToolbar];
        [pickerViewPopup addSubview:monthViewCalendar];
        [pickerViewPopup setBounds:CGRectMake(0, 0, 320, 460)];
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
        
        //[self popUpRefreshFrame];
    
    }else
    {
        [pickerViewPopup showInView:self.view];
        [self popUpRefreshFrame];
    }
        
}

-(void)popUpRefreshFrame
{
    [UIView beginAnimations:@"resize_animation" context:NULL];
    [UIView setAnimationDuration:0.3];
    
    pickerViewPopup.clipsToBounds=YES;
    [pickerViewPopup setFrame:CGRectMake(0.0, 460 - monthViewCalendar.bounds.size.height - 44, 320, monthViewCalendar.bounds.size.height + 44)];
    
    [UIView commitAnimations];
    
    
}

#pragma mark - PickerView Delegate

#pragma mark - PickerView Delegate

-(void) createcurrencyPickerView {
    
    currencyActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; //as we want to display a subview we won't be using the default buttons but rather we're need to create a toolbar to display the buttons on
    
    [currencyActionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    CGRect pickerFrame = CGRectMake(0, 40, 0, 0);
    currencyPickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    currencyPickerView.showsSelectionIndicator = YES;
    currencyPickerView.dataSource = self;
    currencyPickerView.delegate = self;
    [currencyActionSheet addSubview:currencyPickerView];
    
    UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    pickerToolbar.barStyle = UIBarStyleBlackOpaque;
    [pickerToolbar sizeToFit];
    
    NSMutableArray *barItems = [[NSMutableArray alloc] init];
    
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];
    [barItems addObject:doneBtn];
    
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];
    
    UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];
    [barItems addObject:cancelBtn];
    
    [pickerToolbar setItems:barItems animated:YES];
    
    [currencyActionSheet addSubview:pickerToolbar];
    
    [currencyActionSheet addSubview:currencyPickerView];
    
    [currencyActionSheet showInView:self.view];
    
    [currencyActionSheet setBounds:CGRectMake(0, 0, 320, 485)];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
    
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
    
    return [currencyArray count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [currencyArray objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    NSLog(@"Selected Color: %@. Index of selected color: %i", [currencyArray objectAtIndex:row], row);
    currencyTextField.text = [currencyArray objectAtIndex:row];
}

-(void)doneButtonPressed:(id)sender{
    //Do something here here with the value selected using [pickerView date] to get that value
    
    //[pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    [currencyActionSheet dismissWithClickedButtonIndex:1 animated:YES];
    [currencyTextField resignFirstResponder];
}

-(void)cancelButtonPressed:(id)sender{
    // [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];
    [currencyActionSheet dismissWithClickedButtonIndex:1 animated:YES];
    [currencyTextField resignFirstResponder];
}

#pragma mark - Keyboard Show Hide

- (void)keyboardWasShown:(NSNotification *)notification
{
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    NSLog(@"%f,kbsize:%f",activeTextField.frame.origin.y,kbSize.height);
    CGPoint textFieldPosition = CGPointMake(activeTextField.frame.origin.x, activeTextField.frame.origin.y +50);
     NSLog(@"%f,kbsize:%f",textFieldPosition.x,textFieldPosition.y);
    if (!CGRectContainsPoint(aRect, textFieldPosition) ) {
        CGPoint scrollPoint = CGPointMake(0.0, activeTextField.frame.origin.y-kbSize.height +80);
        [scrollView setContentOffset:scrollPoint animated:YES];
    }
}

- (void) keyboardWillHide:(NSNotification *)notification {
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

#pragma mark - Text Field Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return  YES;
}

#pragma mark - Other Notification

- (void) getImageOnSuccess : (NSNotification *) notification {
    NSDictionary *tempDict = [notification object];
    currentImageName = [tempDict objectForKey:@"key"];
    [imagePickerButton setImage:[UIImage imageNamed:currentImageName] forState:UIControlStateNormal];
}
@end
